package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.参数检验
        if (dto==null|| StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询用户信息
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或者密码错误");
        }
        //3.密码加盐
        //数据库密码
        String dbPwd = user.getPassword();
        //用户密码  先把初始密码加盐 然后md5加密
        String uPwd = dto.getPassword()+user.getSalt();
        String newPwd = DigestUtils.md5DigestAsHex(uPwd.getBytes());
        if (!newPwd.equals(dbPwd)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"密码错误");
        }
        //4.修改登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //5.颁发token jwt令牌
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        //6.封装返回结果
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user,adUserVO);
        Map map = new HashMap();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult register(AdUser user) {
        /*//1.参数检验
        if (user==null|| StringUtils.isBlank(user.getName())||StringUtils.isBlank(user.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }*/
        // 用户的密码加密规则是：MD5（密码 + salt）
        String salt = RandomStringUtils.randomAlphanumeric(8);
        String password = user.getPassword();
        user.setPassword( DigestUtils.md5DigestAsHex((password + salt).getBytes()) );
        user.setSalt(salt);
        user.setCreatedTime(new Date());
        user.setStatus(9);
        save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
